package com.example.page.data.pagination

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.page.data.model.Quotes
import com.example.page.data.remote.api.QuotesService
import com.example.page.data.remote.model.toQuotes
import retrofit2.HttpException
import java.io.IOException

/**
 * Quotes PagingSource类
 * @property api QuotesService 实例
 */
class QuotesPagingSource(
    private val api: QuotesService
) : PagingSource<Int, Quotes>() {

    companion object {
        private const val STARTING_KEY = 1
    }

    /**
     * 获取刷新键的方法
     * @param state 当前分页状态
     * @return 刷新键的值, 即当前描点位置
     */
    override fun getRefreshKey(state: PagingState<Int, Quotes>): Int? {
        return state.anchorPosition // 描点位置
    }

    /**
     * 加载指定范围内的分页数据的方法
     * @param params 加载参数, 包含了页数和加载的数据量
     * @return 加载结果, 包含了加载的数据列表 / 前一页的键和后一页的键
     */
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Quotes> {
        val startKey = params.key ?: STARTING_KEY
        return try {
            val quotes = api.getQuotes(startKey, params.loadSize)
            val nextKey = if (quotes.data.isEmpty()) null else quotes.pagination.nextPage
            LoadResult.Page(
                data = quotes.data.map { it.toQuotes(quotes.pagination.currentPage) },
                prevKey = if (startKey == STARTING_KEY) null else startKey - 1,
                nextKey = nextKey
            )
        } catch (e: IOException) {
            return LoadResult.Error(e)
        } catch (httpException: HttpException) {
            return LoadResult.Error(httpException)
        }
    }

}